<template>
  <div class="tree-main-body">
    <div class="left-box">
      <TreeCategory
        :selected="category_ids"
        type="no-cate"
        text="视频"
        @update="handleCateUpdate"
      />
    </div>

    <div class="right-box">
      <div class="d-flex playedu-main-title float-left mb-24">
        视频 | {{ selLabel }}
      </div>

      <div class="float-left j-b-flex mb-24">
        <div class="d-flex">
          <UploadVideoButton
            :categoryIds="category_ids"
            @update="resetVideoList"
          />
          <a-button class="ml-16" @click="toggleMulti">
            {{ multiConfig ? "取消操作" : "批量操作" }}
          </a-button>
          <a-button
            class="ml-16"
            @click="removeResourceMulti"
            :disabled="selectedRowKeys.length === 0"
          >
            删除
          </a-button>
        </div>

        <div class="d-flex">
          <div class="d-flex mr-24">
            <a-typography-text>名称：</a-typography-text>
            <a-input
              v-model:value="title"
              allow-clear
              style="width: 160px"
              placeholder="请输入名称关键字"
            />
          </div>
          <div class="d-flex">
            <a-button class="mr-16" @click="resetVideoList">重 置</a-button>
            <a-button type="primary" @click="queryList">查 询</a-button>
          </div>
        </div>
      </div>

      <!-- 视频表格 -->
      <div class="float-left">
        <a-table
          :row-selection="multiConfig ? rowSelection : null"
          :columns="columns"
          :data-source="videoList"
          :loading="loading"
          :pagination="paginationProps"
          row-key="id"
        >
          <template #bodyCell="{ column, record, text }">
            <!-- 视频名称 -->
            <template v-if="column.dataIndex === 'name'">
              <div class="d-flex">
                <i
                  class="iconfont icon-icon-video"
                  style="font-size:16px;color:rgba(0,0,0,0.3);"
                />
                <span class="ml-8">{{ text }}</span>
              </div>
            </template>

            <!-- 视频时长 -->
            <template v-else-if="column.dataIndex === 'id'">
              <DurationText :duration="videosExtra[record.id]?.duration" />
            </template>

            <!-- 创建人 -->
            <template v-else-if="column.dataIndex === 'admin_id'">
              {{ adminUsers[record.admin_id] }}
            </template>

            <!-- 创建时间 -->
            <template v-else-if="column.dataIndex === 'created_at'">
              {{ dateFormat(record.created_at) }}
            </template>

            <!-- 操作 -->
            <template v-else-if="column.key === 'action'">
              <a-space size="small">
                <a-button
                  type="link"
                  size="small"
                  @click="previewVideo(record)"
                >
                  预览
                </a-button>
                <a-dropdown>
                  <template #overlay>
                    <a-menu>
                      <a-menu-item key="edit">
                        <a-button type="link" @click="editVideo(record.id)">
                          编辑
                        </a-button>
                      </a-menu-item>
                      <a-menu-item key="delete">
                        <a-button
                          type="link"
                          danger
                          @click="removeResource(record.id)"
                        >
                          删除
                        </a-button>
                      </a-menu-item>
                    </a-menu>
                  </template>
                  <a-button type="link">
                    <a-space size="small">
                      更多
                      <DownOutlined />
                    </a-space>
                  </a-button>
                </a-dropdown>
              </a-space>
            </template>
          </template>
        </a-table>
      </div>
    </div>

    <!-- 视频预览 -->
    <VideoPlayDialog
      :id="updateId"
      :open="playVisible"
      :url="playUrl"
      @cancel="playVisible = false"
    />
    <!-- 编辑弹窗 -->
    <VideosUpdateDialog
      :id="updateId"
      :open="updateVisible"
      @cancel="updateVisible = false"
      @success="handleUpdateSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, h } from "vue";
import { useRoute } from "vue-router";
import { Modal, message } from "ant-design-vue";
import { DownOutlined, ExclamationCircleFilled } from "@ant-design/icons-vue";
import { resource } from "@/api";
import { dateFormat } from "@/utils/index";
import TreeCategory from "@/components/Common/tree-category.vue"
import DurationText from "@/components/Common/duration-text.vue"
import UploadVideoButton from "@/components/Common/upload-video-button.vue";
import VideoPlayDialog from "./video-play-dialog.vue";
import VideosUpdateDialog from "./update-dialog.vue";

const { confirm } = Modal;

interface DataType {
  id: number;
  admin_id: number;
  created_at: string;
  name: string;
}

type VideosExtraModel = Record<number, { duration: number; poster: string; rid: number }>;
type AdminUsersModel = Record<number, string>;
type ResourceUrlModel = Record<number, string>;

const route = useRoute();

// 状态
const videoList = ref<DataType[]>([]);
const videosExtra = ref<VideosExtraModel>({});
const adminUsers = ref<AdminUsersModel>({});
const resourceUrl = ref<ResourceUrlModel>({});
const refresh = ref(false);
const page = ref(1);
const size = ref(10);
const total = ref(0);
const loading = ref(true);
const category_ids = ref<number[]>([]);
const selectedRowKeys = ref<any[]>([]);
const selLabel = ref(route.query.label ? String(route.query.label) : "全部视频");
const cateId = ref(Number(route.query.cid) || 0);
const updateVisible = ref(false);
const playVisible = ref(false);
const multiConfig = ref(false);
const updateId = ref(0);
const playUrl = ref("");
const title = ref("");

// 表格列配置
const columns = [
  { title: "视频名称", dataIndex: "name" },
  { title: "视频时长", dataIndex: "id" },
  { title: "创建人", dataIndex: "admin_id" },
  { title: "创建时间", dataIndex: "created_at" },
  { title: "操作", key: "action", fixed: "right", width: 160 },
];

// 获取视频列表
const getVideoList = async () => {
  loading.value = true;
  const categoryIds = category_ids.value.join(",");
  try {
    const res: any = await resource.resourceList(
      page.value,
      size.value,
      "",
      "",
      title.value,
      "VIDEO",
      categoryIds
    );
    total.value = res.data.result.total;
    videoList.value = res.data.result.data;
    videosExtra.value = res.data.videos_extra;
    adminUsers.value = res.data.admin_users;
    resourceUrl.value = res.data.resource_url;
  } catch (err) {
    console.error("错误,", err);
  } finally {
    loading.value = false;
  }
};

// 删除单个
const removeResource = (id: number) => {
  confirm({
    title: "操作确认",
    icon: h(ExclamationCircleFilled),
    content: "删除前请检查选中视频文件无关联课程，确认删除？",
    centered: true,
    okText: "确认",
    cancelText: "取消",
    onOk: async () => {
      await resource.destroyResource(id);
      message.success("删除成功");
      resetVideoList();
    },
  });
};

// 删除多个
const removeResourceMulti = () => {
  if (selectedRowKeys.value.length === 0) return;
  confirm({
    title: "操作确认",
    icon: h(ExclamationCircleFilled),
    content: "删除前请检查选中视频文件无关联课程，确认删除？",
    centered: true,
    okText: "确认",
    cancelText: "取消",
    onOk: async () => {
      await resource.destroyResourceMulti(selectedRowKeys.value);
      message.success("删除成功");
      resetVideoList();
    },
  });
};

// 表格分页
const paginationProps = reactive({
  current: page.value,
  pageSize: size.value,
  total: total.value,
  showSizeChanger: true,
  onChange: (p: number, pageSize: number) => {
    page.value = p;
    size.value = pageSize;
    getVideoList();
  },
});

// 批量选择
const rowSelection = {
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys: any[]) => {
    selectedRowKeys.value = keys;
  },
};

// 分类更新
const handleCateUpdate = (keys: any, title: any) => {
  page.value = 1;
  category_ids.value = keys;
  selLabel.value = typeof title === "string"
    ? title
    : (title?.props?.children?.[0] ?? "全部视频");
  selectedRowKeys.value = [];
  getVideoList();
};

// 重置
const resetVideoList = () => {
  page.value = 1;
  size.value = 10;
  videoList.value = [];
  selectedRowKeys.value = [];
  title.value = "";
  refresh.value = !refresh.value;
  getVideoList();
};

// 查询
const queryList = () => {
  page.value = 1;
  getVideoList();
};

// 编辑
const editVideo = (id: number) => {
  updateId.value = id;
  updateVisible.value = true;
};

// 预览
const previewVideo = (record: any) => {
  updateId.value = record.id;
  playUrl.value = resourceUrl.value[record.id];
  playVisible.value = true;
};

// 编辑成功刷新
const handleUpdateSuccess = () => {
  updateVisible.value = false;
  refresh.value = !refresh.value;
  getVideoList();
};

// 批量开关
const toggleMulti = () => {
  selectedRowKeys.value = [];
  multiConfig.value = !multiConfig.value;
};

onMounted(() => {
  if (cateId.value) {
    category_ids.value = [cateId.value];
  }
  getVideoList();
});
</script>

<style scoped>
</style>
